package com.zero.serialport.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;

import com.zero.serialport.framework.callback.ZeroCallback;
import com.zero.serialport.framework.data.ZeroData;
import com.zero.serialport.framework.decoder.DefaultDecoder;
import com.zero.serialport.framework.port.ZeroPort;

import org.xutils.common.util.LogUtil;

import java.io.IOException;

public class CardService extends Service {



    private ZeroPort zeroPort = null;

    private volatile boolean isAccepted= false;

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtil.d("service init...");
        initPort();
    }

    private void initPort() {
        try {
            zeroPort = new ZeroPort(new ZeroCallback<ZeroData>() {
                @Override
                public void receive(ZeroData data) {
                    if(isAccepted){
                        LogUtil.d(data.toString());
                    }
                }
            },new DefaultDecoder(),2000,"/dev/ttyO5",115200);
        } catch (IOException e) {
            e.printStackTrace();
        }
        zeroPort.start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String command = intent.getStringExtra("command");
        if(command.equals("start")){
            isAccepted = true;
        }
        if(command.equals("end")){
            isAccepted = false;
        }
        if(command.equals("init")){
            LogUtil.d("初始化...");
        }
        LogUtil.d("收到了命令");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        zeroPort.end();
    }
}
